package com.yangcangclub.commons.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口数字签名校验
 */
public class SignUtil {

  //初始化key
  public final static Map keyMap = new HashMap() {
      {
          put("T9NS5830HS0BMNE", "569J17FE591544C48AF24569C9AAA6E1B67B3");
          put("NC83NS74NAOGJA0", "8FGA744F2FEB3435F354392664242E7B88425");
      }
  };

    public static boolean signCheck(HttpServletRequest request){
        String key=request.getParameter("key");
        String sign=request.getParameter("sign");

        if(sign==null|key==null||keyMap.get(key)==null){
            return false;
        }else{
            Map<String,Object[]> map= request.getParameterMap();
            Collection<String> keyset= map.keySet();
            List<String> list = new ArrayList<String>(keyset);

            //对key键值按字典升序排序
            Collections.sort(list);

            StringBuilder str=new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                if("key".equals(list.get(i))||"sign".equals(list.get(i))||"version".equals(list.get(i))){
                    continue;
                }

                str.append(list.get(i)).append("=").append(map.get(list.get(i))[0]).append("&");

            }

           String temp= str.toString().substring(0,str.toString().length()-1);
            //签名校验
          return sign.equalsIgnoreCase(SHA1.encode(keyMap.get(key)+temp));
        }

    }
}
